package com.example.common.interceptors;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.java.Log;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import com.example.common.context.BaseContext;

public class UserInfoInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1. 获取用户信息
        String userInfo = request.getHeader("user-info");

        System.out.println("userInfo:"+userInfo);
        // 2. 判断是否获取了用户信息， 如果有存到ThreadLocal线程变量中。
        if (StringUtils.isNotBlank(userInfo)) {
            Long userId = Long.valueOf(userInfo);
            BaseContext.setCurrentId(userId);
        }
        // 3. 放行
        return true;

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        BaseContext.removeCurrentId();
    }
}
